<?php

/**
 * 后台管理类
 */
class adminModel
{
    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
    }
    /**
     * 带图片的帖子总数
     * @param
     * @return intval $num
     */
    public function getTotalPostNumWithImg()
    {

        $sql = "select count(*) from r_news where is_show = 1 and sourceImg != '' and sourceImg != '[]' and uid > 0";

        $num = $this->db->getone($sql);
        $num = intval($num);

        return $num;
    }
    /**
     * 用户带图片的帖子总数
     * @param
     * @return intval $num
     */
    public function userTotalPostNumWithImg($uid)
    {

        $uid = intval($uid);
        $sql = "select count(*) from r_news where uid = '{$uid}' and is_show = 1 and sourceImg != '' and sourceImg != '[]' and uid > 0";

        $num = $this->db->getone($sql);
        $num = intval($num);

        return $num;
    }
    /**
     * 带图片的帖子列表
     * @param int $p  页码
     * @param int $offset  条数
     * @return array $postList
     */
    public function getPostWithImg($p = 1, $offset = 20)
    {
        $p = intval($p);
        $offset = intval($offset);

        !$p && $p = 1;
        !$offset && $offset = 20;
        $start = ($p -1) * $offset;

        $sql = "select news_id, uid, sourceImg from r_news where is_show = 1 and sourceImg != '' and sourceImg != '[]' and uid > 0 order by add_time DESC limit $start, $offset";
        
        $result = $this->db->getAll($sql);
        empty($result) && $result = array();

        return $result;
    }
    /**
     * 用户发表的带图片的帖子列表
     * @param int $uid 用户id
     * @param int $duration 帖子发表时间限制
     * @return array()
     */
    public function userPostImgList($uid, $p = 1, $offset = 20)
    {
        if(!$uid)
        {
            return array();
        }

        $p = intval($p);
        $offset = intval($offset);
        $p <= 0 && $p = 1;
        $offset <= 0 && $offset = 20;

        $start  = ($p - 1) * $offset;

        $sql = "select news_id, sourceImg from r_news where uid = '{$uid}' and is_show = 1 and sourceImg != '' and sourceImg != '[]' order by add_time DESC limit $start, $offset";

        return $this->db->getAll($sql);
    }
    /**
     * 推荐好友 添加/移除 用户-图片到备选列表
     * @param int $uid
     * @param string $img
     * @param boolen $isAdd
     * @return boolen
     */
    public function friendRecAddAlternate($uid, $sourceImg, $isAdd)
    {
        if(!$uid || !$sourceImg)
        {
            return $result;
        }

        $addTime = $this->base->time;
        $updatetime = $addTime;

        $nowStatus = $this->db->getone("select status from r_friendRecList where uid ='{$uid}' and sourceImg = '{$sourceImg}'");

        if($nowStatus === false)
        {
            $data['addTime'] = $addTime;
        } 
        else if($nowStatus == 2)
        {
            return 2;
        }

        $status = $isAdd ? 1 : 0;
        $data = compact('uid', 'sourceImg', 'status', 'updatetime');

        return $this->db->insertRowTable('r_friendRecList', $data) !== false;
    }
    /**
     * 推荐好友 备选用户总数
     * @param
     * @return intval $num
     */
    public function friendRecAlternateNum()
    {
        $sql = "select count(distinct(uid)) from r_friendRecList where status in ('1', '2', '3') ";

        $num = $this->db->getone($sql);
        $num = intval($num);

        return $num;
    }
    /**
     * 推荐好友 备选用户-图片列表
     * @param int $p  页码
     * @param int $offset  条数
     * @return array $postList
     */
    public function friendRecAlternateList($p = 1, $offset = 20)
    {
        $p = intval($p);
        $offset = intval($offset);

        !$p && $p = 1;
        !$offset && $offset = 20;
        $start = ($p -1) * $offset;

        $sql = "select distinct(uid) as uid from r_friendRecList where status in ('1', '2', '3') order by addTime DESC limit $start, $offset";
        $userList = $this->db->getCol($sql);

        $result = array();
        if($userList)
        {
            foreach ($userList as $uid)
            {
                $imgs = $this->db->getAll("select sourceImg, status from r_friendRecList where uid = '{$uid}' and status in ('1', '2', '3') order by status DESC, addTime DESC");
                $result[] = array('uid' => $uid,
                                  'imgs' => $imgs
                        );
            }
        }
        empty($result) && $result = array();

        return $result;
    }
    /**
     * 设置为推荐好友
     * @param
     * @return boolen
     */
    public function setRecommendFriendList($uid)
    {
        $result = false;
        $redisKey = REDIS_PREFIX.'RecFriList';
        if($uid)
        {
            $result = $this->redis->SADD($redisKey, $uid) !== false;
        }
        
        return $result;
    }
    /**
     * 取消推荐好友
     * @param
     * @return boolen
     */
    public function remRecFriend($uid)
    {
        $result = false;
        $redisKey = REDIS_PREFIX.'RecFriList';
        if($uid)
        {
            $result = $this->redis->SREM($redisKey, $uid) !== false;
            if($result)
            {
                $updatetime = $this->base->time;
                $this->db->update("update r_friendRecList set status = 3, updatetime = '{$updatetime}' where uid = '{$uid}' and status = 2");
                $this->redis->hdel(REDIS_PREFIX.'RecFriendImg', $uid);
            }
        }
        
        return $result;
    }
    /**
     * 设置推荐好友展示图
     * @param
     * @return array()
     */
    public function setRecFriendImg($uid, array $img)
    {
        $result = false;
        if($uid && !empty($img))
        {
            $data = array('uid' => $uid, 'status' => 2,'updatetime' => $this->base->time);
            $recImages = array();
            foreach ($img as $v)
            {
                $data['sourceImg'] = $v['sourceImg'];    
                $data['recImg'] = $v['recImg'];
                $this->db->updateRowTable('r_friendRecList', $data);
                $recImages[] = $v['recImg'];
            }
            $this->db->update("update r_friendRecList set status = 1 where uid = '{$uid}' and status = 2 and recImg not ".$this->base->load('push')->db_create_in($recImages));
            $this->redis->hset(REDIS_PREFIX.'RecFriendImg', $uid, json_encode($recImages)) !== false && $result = true;
        }
        return $result;
    }
    /**
     * 获取推荐群组数量
     * @param
     * @return int
     */
    public function getRecommendGroupNum()
    {
        $num = $this->db->getone("select count(*) from r_group_recommend where is_delete = 0");

        return $num;
    }
    /**
     * 加入推荐群组
     * @param int $gid
     * @return boolen
     */
    public function addRecommendGroup($gid)
    {
        $result = false;
        $time = $this->base->time;
        $insertArray = array('gid' => $gid,
                            'add_time' => $time,
                            'updatetime' => $time,
                            'is_delete' => 0
            );

        return $this->db->insertRowTable('r_group_recommend', $insertArray) !== false;
    }
    /**
     * 移除推荐群组
     * @param int $gid
     * @return boolen
     */
    public function remRecommendGroup($gid)
    {
        $result = false;
        if($this->db->query("select * from r_group_recommend where gid = '{$gid}' and is_delete = 0"))
        {
            $time = $this->base->time;
            $updateArray = array('gid' => $gid,
                                'updatetime' => $time,
                                'is_delete' => 1
                );
            $result = $this->db->updateRowTable('r_group_recommend', $updateArray) !== false;
        }

        return $result;
    }
    /**
     * 某帖子是否为热门帖子
     * @param int $postId
     * @return boolen
     */
    public function isHotPost($postId)
    {
        return $this->redis->ZRANK(REDIS_PREFIX.'TopHotpost', $postId) !== FALSE;
    }
    /**
     * 取消某帖子热门帖子，并屏蔽
     * @param int $postId
     * @return boolen
     */
    public function ignoreHotPost($postId)
    {
        // 从热门帖子列表中移除
        $this->redis->ZREM(REDIS_PREFIX.'TopHotpost', $postId);

        // 将该帖子加入到热门帖子屏蔽列表中
        return $this->redis->SADD(REDIS_PREFIX.'TopHotIGPost', $postId) !== FALSE;
    }
    /**
     * 取消屏蔽某帖子热门帖子
     * @param int $postId
     * @return boolen
     */
    public function cancleIgnoreHotPost($postId)
    {
        // 将该帖子加入到热门帖子屏蔽列表中
        return $this->redis->SREM(REDIS_PREFIX.'TopHotIGPost', $postId) !== FALSE;
    }
/**------------2.5.0首页热门--------------**/
 /**
     * 某帖子是否为热门帖子
     * @param int $postId
     * @return boolen
     */
    public function isHotPost2($postId)
    {
        return $this->redis->ZRANK(REDIS_PREFIX.'BbsBestPost', $postId) !== FALSE;
    }
    /**
     * 取消某帖子热门帖子，并屏蔽
     * @param int $postId
     * @return boolen
     */
    public function ignoreHotPost2($postId)
    {
        // 从热门帖子列表中移除
        $this->redis->ZREM(REDIS_PREFIX.'BbsBestPost', $postId);

        // 将该帖子加入到热门帖子屏蔽列表中
        return $this->redis->SADD(REDIS_PREFIX.'BbsBestIGPost', $postId) !== FALSE;
    }
    /**
     * 取消屏蔽某帖子热门帖子
     * @param int $postId
     * @return boolen
     */
    public function cancleIgnoreHotPost2($postId)
    {
        // 将该帖子加入到热门帖子屏蔽列表中
        return $this->redis->SREM(REDIS_PREFIX.'BbsBestIGPost', $postId) !== FALSE;
    }

/**------------2.5.0首页热门结束--------------**/




    /**
     * 添加装备配色
     * @param int $gearId
     * @return boolen
     */
    public function addGearBlendent($gearId, $blendent)
    {
        if(!$gearId || !isset($blendent['color']) || !isset($blendent['img']))
        {
            return FALSE;
        }

        $blendent['gearId'] = $gearId;
        
        return $this->db->insertRowTable('r_gear_blendent', $blendent) !== FALSE;
    }
    /**
     * 删除装备配色
     * @param int $id
     * @param int $gearId
     * @return boolen
     */
    public function delBlendent($gearId, $id)
    {
        if(!$gearId || !$id)
        {
            return FALSE;
        }

        return $this->db->query("update r_gear_blendent set is_delete = 1 where gearId = '{$gearId}' and id = '{$id}'") !== FALSE;
    }
    /**
     * 活动总数
     * @param
     * @return int
     */
    public function getActivityNum()
    {
        $num = $this->db->getone('select count(*) from r_activity');
        return intval($num);
    }
    /**
     * 活动列表
     * @param int p 页码
     * @return array
     */
    public function getActivityList($p = 0 , $listNum = 10)
    {
        $p = intval($p);
        $listNum = intval($listNum);
        $start = ($p - 1) * $listNum;

        $result = $this->db->getAll("select * from r_activity order by act_id DESC limit $start, $listNum");

        return $result;
    }

    /**
     * 更新活动信息
     * @param int $act_id
     * @param array $activityInfo
     * @return boolen
     */
    public function updateActivity($act_id, $activityInfo)
    {
        if(!$act_id || empty($activityInfo))
        {
            return false;
        }

        $activityInfo['act_id'] = $act_id;

        return $this->db->updateRowTable('r_activity', $activityInfo) !== false;
    }

    /**
     * 添加活动
     * @param array $activityInfo
     * @return boolen
     */
    public function addActivity($activityInfo)
    {
        if(empty($activityInfo))
        {
            return false;
        }

        return $this->db->insertRowTable('r_activity', $activityInfo);
    }
    /**
     * 获取版块附加模块
     * @param string boardId
     * @return array 
     */
    public function getBoardAdditions($boardId = '')
    {
        if(!$boardId)
        {
            return array();
        }

        $result = $this->db->getAll("select * from r_board_addition where board = '{$boardId}'");

        return $result;
    }
    /**
     * 更新版块附加模块
     * @param string boardId
     * @param array addition
     * @return array 
     */
    public function updateBoardAddition($id, $addition)
    {
        if(!$id)
        {
            return false;
        }

        $addition['id'] = $id;
        $result = $this->db->updateRowTable('r_board_addition', $addition) != false;

        return $result;
    }

    /*
     * 根据帖子内容获取新内容，缩略图、原图
     * string $content
     * return array('content','sourceImg','thumb_img')
    */
    public function digPostImg($content)
    {
        $thumb_img = array();
        $sourceImg = array();
        $content = str_ireplace('<span style="display:none;"></span>', '', $content);
        $content = str_ireplace('?imageView2/2/w/720', '', $content);
        $content = preg_replace('/<a\shref=\".*\"><\/a>/U', '', $content);
        // 删除图片地址为本地路径的图片
        $content = preg_replace('/<a\shref=\"joggers:\/\/topic\/image\/.*\"><img.*src=\"file.*\".*\/><\/a>/U', '', $content);
        $content = preg_replace('/<img.*src=\"file.*\".*\/></U', '', $content);

        // 删除图片外围的a标签
        $content = preg_replace('/<a\shref=\"joggers:\/\/topic\/image\/.*\">(<img.*src=.*\/>)<\/a>/U', '${1}', $content);

        preg_match_all('/<img\s.*src=\"(.*)\".*\/?>/U', $content, $matchs);
        $htmlTag = $matchs[0];
        $source = $matchs[1];
        foreach ($htmlTag as $key => $h)
        {
            $newHtml = '<a href="joggers://topic/image/'.$source[$key].'">'.str_replace($source[$key], $source[$key].'?imageView2/2/w/720', $h).'</a>';
            $content = str_replace($h, $newHtml, $content);
            unset($newHtml);
        }
        preg_match_all('/<a\shref=\"joggers:\/\/topic\/image\/(.*)">/U', $content, $imgs);
        $sourceImg = $imgs[1];
        extract($this->base->config['qiniu']);
        foreach ($sourceImg as $key => $img)
        {
            if(stripos($img, 'static/kindeditor/plugins/emoticons/images') != false)
            {
                continue;
            }
            stripos($img, '?') && $img = substr($img, 0, stripos($img, '?'));
            $imgTmp = explode('/', $img);
            $imgName = 'thumb'.end($imgTmp);
            if(common::is_json(common::getContents('http://'.$bucket.'.'.$host.$imgName)) != true)
            {
                // $thumb_img[] = 'http://'.$bucket.'.'.$host.$imgName.'?imageMogr2/thumbnail/200x200!';
                $thumb_img[] = 'http://'.$bucket.'.'.$host.$imgName;
            }
            else
            {
                $sourceSize = common::getContents($img.'?imageInfo');
                $sourceSize = json_decode($sourceSize, true);
                if(is_array($sourceSize) && !isset($sourceSize['error']))
                {
                    $sourceSize[0] = $sourceSize['width'];
                    $sourceSize[1] = $sourceSize['height'];
                    $tmpImg = $this->base->load('bbs')->qiNiuCropImg($img, $sourceSize, $imgName);
                    if(!empty($tmpImg))
                    {
                        stripos($img, '.gif') !== false && $tmpImg = $this->base->load('bbs')->qiNiuWaterMark($tmpImg);
                        $thumb_img[] = $tmpImg;
                    }
                }
            }
        }
        return compact('content','sourceImg','thumb_img');
    }
}
